package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程的任务是与指定的客户端完成HTTP交互
 * HTTP协议要求一问一答
 * 对此,这里的处理大致分为三步
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            /*
                测试读取请求行
                请求行是请求的一行内容,以回车符+换行符结尾的一行字符串
             */
            String line = readLine();
            System.out.println("请求行:"+line);
            String method;
            String uri;
            String protocol;
            //请求行:GET /index.html HTTP/1.1

            String[] split = line.split("\\s");
            method = split[0];
            uri = split[1];
            protocol = split[2];
            System.out.println(method+","+uri+","+protocol);
            //2处理请求
            Map<String,String> headers = new HashMap<>();
            while (true){
                line = readLine();
                if(line.isEmpty()){
                    break;
                }
                System.out.println("消息头:"+line);
                split = line.split(":\\s");
                headers.put(split[0],split[1]);
            }
            headers.forEach((k,v)-> System.out.println(k+":"+v));
            //3发送响应

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();//保存拼接后的一行字符串
        char cur='a',pre='a';//cur表示本次读取的字符  pre表示上次读取的字符
        while((d = in.read())!=-1){
            cur = (char)d;//将本次读取的字符赋值给cur
            if(pre==13 && cur==10){//判断上次是否读取的回车符,本次是否为换行符
                break;//若连续读取了回车+换行就停止读取(一行结束了)
            }
            builder.append(cur);
            pre=cur;//在读取下一个字符前,将本次读取的字符记作"上次读取的字符"
        }
        String line = builder.toString().trim();
        return line;
    }


}
